package com.kaifamiao.trace;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

@WebServlet( "/cookie/produce" )
public class CookieProduceServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void service( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        logger.info( "创建Cookie实例" );
        // 通过 Cookie 类的构造方法创建 Cookie 实例
        Cookie cookie = new Cookie( "username" , "zhangmazi" );

        logger.info( "设置Cookie实例" );
        // cookie.setDomain( "www.kaifamiao.com" ); // 设置域 ( 可以由容器来设置 )

        cookie.setPath( "/" ); // 设置路径

        int expiry = 60 * 60 * 24 * 7 ;
        cookie.setMaxAge( expiry ); // 以秒为单位设置cookie的有效期

        // secure 为 true 表示仅限安全连接才会向客户端发送 cookie
        // secure 为 false 表示任意连接都会向客户端发送 cookie
        cookie.setSecure( true ); // 对于本机操作没有影响 ( localhost 或 127.0.0.1 )

        // httpOnly 为 false 表示允许在客户端通过 JavaScript 脚本来访问 cookie
        // httpOnly 为 true 则表示仅限 http 请求时使用该 cookie ，客户端脚本不可访问
        cookie.setHttpOnly( false ); // 是否允许客户端脚本访问

        logger.info( "将Cookie添加到响应头" );
        // 将 cookie 添加到 响应头 ( response header )
        response.addCookie( cookie );

        response.addCookie( new Cookie( "kaifamiaoid" , "12345" ) );

        // 尝试从 响应对象 中获取 指定名称的 响应头字段
        logger.info( "set-cookie: " + response.getHeaders( "set-cookie" ) );

        PrintWriter out = response.getWriter();
        out.println( "<p>Cookie</p>");

        out.println( "<script src=\"/cookie.js\"></script>");

    }
}
